package com.imflea.zero.service.pay.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.constant.PayConstant;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.dao.pay.PayRecoderInfoMapper;
import com.imflea.zero.model.entity.pay.PayRecorderInfo;
import com.imflea.zero.model.entity.pay.dto.PayRecorder4QueryDto;
import com.imflea.zero.model.entity.pay.dto.PayRecorderInfoDto;
import com.imflea.zero.model.entity.pay.dto.PaySuccessDto;
import com.imflea.zero.service.pay.IPayRecorderInfoService;
import com.imflea.zero.utils.SessionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 支付记录 服务实现类
 * </p>
 *
 * @author xiangbaoyu
 * @since 2021-09-27
 */
@Service
public class PayRecorderInfoServiceImpl extends ServiceImpl<PayRecoderInfoMapper, PayRecorderInfo> implements IPayRecorderInfoService {
//    @Autowired
//    private IAdoptOrderInfoService adoptOrderInfoService;


    @Override
    public PayRecorderInfo saveOrUpdatePayRecoderInfo(PayRecorderInfo entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
        }
        entity.setTenantId(SessionUtils.getTenantId());
        boolean result = this.saveOrUpdate(entity);
        if (!result) {
            throw new BizException("创建支付交易记录失败");
        }
        return entity;
    }

    @Override
    public PageInfo<PayRecorderInfo> queryPage(PayRecorderInfoDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<PayRecorderInfo> adoptInfos = this.list(queryWrapper);
        PageInfo<PayRecorderInfo> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public PayRecorderInfo queryByOrderSn(String sn) {
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn", sn);
        queryWrapper.orderByDesc("pay_time");

        List<PayRecorderInfo> recoderInfos = this.list(queryWrapper);
        if (!CommonUtils.isNull(recoderInfos)) {
            return recoderInfos.get(0);
        }
        return null;
    }

    @Override
    public Boolean updateStatus(String id, String status) {

        if (CommonUtils.isNull(id)) {
            throw new BizException("缺少支付记录id");
        }
        if (CommonUtils.isNull(status)) {
            throw new BizException("缺少支付记录状态");
        }
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("tenant_id", SessionUtils.getTenantId());
        PayRecorderInfo info = this.getOne(queryWrapper);
        info.setPayStatus(status);
        Boolean result = this.updateById(info);
        if (!result) {
            throw new BizException("更新支付状态失败");
        }
        return result;
    }

    @Override
    public PayRecorderInfo getByOrderSn(String orderSn) {
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_sn", orderSn);
        PayRecorderInfo recorderInfo = this.getOne(queryWrapper);
        return recorderInfo;
    }

    @Override
    public PageInfo<PayRecorderInfo> queryPage(PayRecorder4QueryDto dto) {

        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", tenantId);
        if (!CommonUtils.isNull(dto.getOrderSn())) {
            queryWrapper.eq("order_sn", dto.getOrderSn());
        }
        if (!CommonUtils.isNull(dto.getOrderType())) {
            queryWrapper.eq("order_type", dto.getOrderType());
        }
        if (!CommonUtils.isNull(dto.getPayType())) {
            queryWrapper.eq("pay_type", dto.getPayType());
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<PayRecorderInfo> adoptInfos = this.list(queryWrapper);
        PageInfo<PayRecorderInfo> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public PayRecorderInfo updatePayRecorderStatus2Finish(String recoderId) {

        PayRecorderInfo payRecorderInfo = this.getById(recoderId);
        if (CommonUtils.isNull(payRecorderInfo)) {
            throw new BizException("该支付交易记录不存在");
        }
        String tenantId = SessionUtils.getTenantId();
        String waitTenantId = payRecorderInfo.getTenantId();
        if (!tenantId.equals(waitTenantId)) {
            throw new BizException("越权，非法操作");
        }
        String status = payRecorderInfo.getPayStatus();
        String paySn = payRecorderInfo.getPaySn();
        String payType = payRecorderInfo.getPayType();
        if (PayConstant.PAY_STATUS_WAIT_CONFIRM.getCode().equals(status)) {
            String updatedStatus = PayConstant.PAY_STATUS_FINISH.getCode();
            this.updateStatus(recoderId, updatedStatus);
            //通知订单
            List<PaySuccessDto> dtos = new ArrayList<>();
            PaySuccessDto dto = new PaySuccessDto();
            dto.setPaySn(paySn);
            dto.setPayType(payType);
            dto.setOrderId(payRecorderInfo.getOrderId());
            dtos.add(dto);


            boolean chageOrderResult = false;


            if (!chageOrderResult) {
                throw new BizException("订单状态更新失败");
            }
            return payRecorderInfo;

        } else {
            if (PayConstant.PAY_STATUS_FINISH.getCode().equals(status)) {
                throw new BizException("该订单已确认支付完成，重复操作");
            } else {

            }
            throw new BizException("支付交易记录状态异常：" + PayConstant.getName(status));
        }
    }

    @Override
    public boolean removeByOrderIds(List<String> orderIds) {
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("order_id", orderIds);
        boolean result = this.remove(queryWrapper);
        return result;
    }

    @Override
    public List<PayRecorderInfo> queryByOrderIds(List<String> orderIds) {
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("order_id", orderIds);
        List<PayRecorderInfo> result = this.getBaseMapper().queryByOrderIds(orderIds);


        return result;

    }

    @Override
    public PayRecorderInfo queryByPaySn(String paySn) {
        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pay_sn", paySn);
        PayRecorderInfo recorderInfo = this.getOne(queryWrapper);
        return recorderInfo;
    }

    @Override
    public List<PayRecorderInfo> queryWaitHandleRecorder() {

        QueryWrapper<PayRecorderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pay_type", PayConstant.PAY_TYPE_TRANSFER.getCode()).and(item -> item.eq("pay_status", PayConstant.PAY_STATUS_WAIT_CONFIRM.getCode()).or(i -> i.eq("pay_status", PayConstant.PAY_STATUS_WAIT_UPLOAD_RECEIVE_PROOF.getCode())));


        return this.list(queryWrapper);
    }


}
